import axios from 'axios';
import { Message, MessageBox } from 'element-ui';
import store from '../store';

const serialize = function(obj, prefix) {
    const str = [];
    for (const p in obj) {
        if (obj.hasOwnProperty(p)) {
            const k = prefix ? prefix + '[]' : p, v = obj[p];
            str.push(v !== null && typeof v === 'object' ?
                serialize(v, k) :
                encodeURIComponent(k) + '=' + encodeURIComponent(v));
        }
    }
    return str.join('&');
}

function isUndefined(val) {
    return val !== null && typeof val === 'object';
}

function setContentTypeIfUnset(headers, value) {
    if (!isUndefined(headers) && isUndefined(headers['Content-Type'])) {
        headers['Content-Type'] = value;
    }
}

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  withCredentials: true,         // 跨域请求允许带cookie
  timeout: 5000,                  // 请求超时时间
  transformRequest: [function transformRequest(data, headers) {
    // modify default action
    if (data !== null && typeof data === 'object') {
        setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
        return serialize(data);
    }
    return data;
  }]
});

// request拦截器
service.interceptors.request.use(config => {
  return config;
}, error => {
  // Do something with request error
  console.log(error); // for debug
  Promise.reject(error);
})

// respone拦截器
service.interceptors.response.use(
  response => {
  /**
  * code为非0是抛错
  */
    const res = response.data;
    if (res.code !== 0) {
      // 5003 用户未登录
      if (res.code === 5003) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload();// 为了重新实例化vue-router对象 避免bug
          });
        })
      } else {
          Message({
              message: res.msg,
              type: 'error',
              duration: 3 * 1000
          });
      }
      return Promise.reject(response.data);
    } else {
      return response.data;
    }
  },
  error => {
    console.log('err' + error);// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    });
    return Promise.reject(error);
  }
)

export default service;
